import axios from "axios";
import { ElMessage,ElMessageBox } from 'element-plus';

const myAxios = axios.create({
    // baseURL: 'http://ip.w7.cc',
    timeout: 9000
});

myAxios.interceptors.request.use(config => {
    return config;
}, err => {
    Promise.reject(err)
})

myAxios.interceptors.response.use(res => {
    if(res.status==200 && res){
        return Promise.resolve(res)
    }
}, error => {
    if(error?.response?.status == 401){
        // return;
    }
    if(error?.response?.status == 422){
        let errorinfo = error.response.data.errors;
        let keys = Object.keys(errorinfo);
        let messages = keys.map(key => {
            return errorinfo[key].join('\n');
        });
        ElMessageBox.alert(messages.join('<br/>'),"提示",{confirmButtonText:"确定",dangerouslyUseHTMLString:true});
        Promise.reject(error)
        return;
    }
    if(error.response && !error.config.headers.cancelerror) {
        ElMessage({
            message: (error.response.data && error.response.data.error) ? error.response.data.error : '出错了',
            duration: 3000,
            type:'error',
        });
    }
    Promise.reject(error)
});

export default myAxios;